<?php

namespace app\common\business;

use app\common\lib\Arr;
use app\common\lib\Str;
use app\common\lib\Time;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\Exception;

class AdminUser{

    public $model = null;

    public function __construct()
    {
        $this->model = new \app\common\model\mysql\AdminUser();
    }

    /**
     * @throws Exception
     */
    public function login($data){
        try {
            $adminUser = self::getAdminUserByUserName($data['username']);
            if (empty($adminUser)){
                throw new Exception("该用户不存在或被禁用");
            }
            //判断密码是否正确
            if ($adminUser['password'] != Str::getUserPassword($data['password'])) {
                throw new Exception("密码错误");
            }

            //需要记录信息到mysql表中
            $updateData = [
                "last_login_time" => time(),
                "last_login_ip" => request()->ip()
            ];
            $res = $this->model->updateById($adminUser['id'], $updateData);
            if (!$res) {
                throw new Exception("登录失败");
            }
        } catch (\Exception $e) {
            throw new Exception($e->getMessage());
        }

        $token = Str::getLoginToken($data['username']);
        $redisData = [
            "id" => $adminUser['id'],
            "username" => $data['username'],
            "roles" => $adminUser['roles'],
            "area_id" => $adminUser['area_id'],
        ];
        $res = cache(config("redis.admin_token_pre") . $token, $redisData, Time::userLoginExpiresTime(1));//过期时间 1：7天 2：30天

        return $res ? ["token" => $token, "username" => $data['username'],"id"=>$adminUser['id']] : false;
    }

    /**
     * 通过用户名获取用户数据
     * @param $username
     * @return array|false
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function getAdminUserByUserName($username){
        $adminUser = $this->model->getAdminUserByUsername($username);
        if (empty($adminUser) || $adminUser->status != config("status.mysql.table_normal")) {
            return false;
        }
        return $adminUser->toArray();
    }

    /**
     * 根据当前用户id查询用户信息
     * @param $id
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws Exception
     * @throws ModelNotFoundException
     */
    public function getAdminUserById($id): array
    {
        if(empty($id)){
            throw new Exception('参数错误');
        }
        $user=$this->model->getAdminUserById($id);
        if (empty($user)) {
            throw new Exception('用户不存在,请重新登录');
        }
        if(empty($user['role'])){
            throw new Exception('该用户未分配角色，请联系管理员');
        }
        $user['role']['rules']=explode(';',$user['role']['rules']);
        return $user->toArray();
    }
    /**
     * 获取分页列表
     * @throws Exception
     */
    public function getTableList($page=null,$limit=null,$keyword=''): array
    {
        $where=[
            ['username|real_name','like','%'.$keyword.'%']
        ];
        $list=$this->model->getTableList($where,$page,$limit);

        if (!empty($list['list'])){
            //字典
            $categoryIdArr = array_column($list['list'],'area_id');
            $mapCategory = [
                ['id','in',$categoryIdArr]
            ];
            $categoryData = (new \app\common\business\Category())->getListByWhere($mapCategory,0,0,'id,name');
            $categoryArr = Arr::getKeyValueByTwoArray($categoryData,'','id',2);

            foreach ($list['list'] as $k=>$v){
                $list['list'][$k]['area_text'] = isset($categoryArr[$v['area_id']]) ? $categoryArr[$v['area_id']]['name'] : '';
                $list['list'][$k]['last_login_time']=Time::formatTheTime($v['last_login_time'],'s');

            }
        }
        return $list;
    }
    /**
     * 新增/保存数据
     * @param $data
     * @return bool
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException|Exception
     */
    public function save($data): bool
    {
        if(empty($data['id'])){
            $repeat=self::checkUsernameRepeat($data['username']);
            if($repeat){
                throw new Exception('账号重复');
            }
            unset($data['id']);
        }

        if (isset($data['password'])){
            $data['password']=Str::getUserPassword($data['password']);
        }

        return $this->model->saveData($data);
    }

    /**
     * 检验新增的用户名是否存在
     * @param $username
     * @return bool
     */
    public function checkUsernameRepeat($username): bool
    {
        return $this->model->where(['username'=>$username])->count()>0;
    }

    /**
     * 根据id修改状态
     * @param $data
     * @return bool
     * @throws DataNotFoundException
     * @throws DbException
     * @throws Exception
     * @throws ModelNotFoundException
     */
    public function updateStatus($data): bool
    {
        if(empty($data['id'])){
            throw new Exception('参数错误');
        }
        return $this->model->updateStatus($data);
    }
    /**
     * 根据id删除
     * @param $id
     * @return bool
     * @throws Exception
     */
    public function deleteById($id): bool
    {
        if(empty($id)){
            throw new Exception('参数错误');
        }
        return $this->model->deleteById($id);
    }
}
